//
//  OrdersViewController.m
//  Manager
//
//  Created by 彭凯敏 on 15/8/18.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "OrdersViewController.h"
#import "OrderInfoViewController.h"
#import "GetOrderViewController.h"
#import "OrderCell.h"
#import "ViewRoomLogic.h"
#import "Viewroom.pb.h"
#import "ViewOrderModel.h"

#import <MJRefresh.h>

typedef void(^RequestStewardFinishBlock)(BOOL isFinish);//接单成功

@interface OrdersViewController ()<orderCellDelegate>
{
    NSMutableArray *dataArray;
    NSMutableArray *timeArray;
    
    RequestStewardFinishBlock finishBlock;
    
}
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSTimer *refreshTimer;
@end

@implementation OrdersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog(@"viewDidLoad");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderDataChanged:) name:Notifi_Order_Data object:nil];
    [self createUI];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestSuccessSteward:) name:CMD_ViewRoom_StewardOrder object:nil];
    
    dataArray = [[NSMutableArray alloc]init];
    
    _refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(exceedTime) userInfo:nil repeats:YES];
    
    [self reloadData];
    [self queryOrderRequest];
    
    
    
}
- (void)createUI
{
    [self homeBaseCtlSetTitle:@"接单列表" andWithBackType:BackZero];
    [self baseCtlSetLeftBtnTitle:nil andWithRightTitle:@"查看房源"];
    
    [self.rightNavgationItem setAction:@selector(clickRoom:)];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64-49) style:UITableViewStylePlain];
    [_tableView setLineType:TableViewLineTypeAll];
    _tableView .delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [_tableView setLineType:TableViewLineTypeAll];

    __weak __typeof(self) weakSelf = self;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf queryOrderRequest];
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    DLog(@"viewWillDisappear");
    [_refreshTimer setFireDate:[NSDate distantFuture]];
}

- (void)viewWillAppear:(BOOL)animated
{
    DLog(@"viewWillAppear");
    [_refreshTimer setFireDate:[NSDate date]];
}

-(void)viewDidUnload {
    DLog(@"viewDidUnload");
}

-(void)dealloc {
    DLog(@"dealloc");
}

#pragma mark - refreshArray

- (void)startTimerWith:(NSArray *)array
{
    [_refreshTimer setFireDate:[NSDate date]];
    
    if (!timeArray) {
        timeArray = [[NSMutableArray alloc]init];
    }
    
    [timeArray removeAllObjects];
    
    for (NSInteger i = 0;i<array.count;i++) {
        ViewOrderModel *model = array[i];
        
        if (model.order.status == 1) {
            [timeArray addObject:[NSString stringWithFormat:@"%llu",model.order.createTime/1000]];
        }
        else if (model.order.status == 2)
        {
            [timeArray addObject:[NSString stringWithFormat:@"%llu",model.order.orderStewardTime/1000]];
        }
    }
    
}
//是否超时10分钟
- (void)exceedTime
{
    DLog(@"exceedTime");
    if (!timeArray) {
        return;
    }
    int num =0;
    for (NSInteger i = 0; i<dataArray.count; i++) {
        OrderCell *cell = (OrderCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];

        if (![[self exceedTimeWith:timeArray[i]  WithLabel:cell.btnAssisLabel] isEqualToString:@"超时十分钟"]) {
            num++;
        }
    }
    if (num == 0) {
       [_refreshTimer setFireDate:[NSDate distantFuture]];
    }
    
}
//是否超时10分钟
- (NSString *)exceedTimeWith:(NSString *)getTime WithLabel:(UILabel *)label
{
    NSDate *getDate = [NSDate dateWithTimeIntervalSince1970:[getTime longLongValue]];
    
    NSDate *nowDate = [NSDate date];
    
    NSTimeInterval time=[nowDate timeIntervalSinceDate:getDate];
    time = 10*60- time;
    int minute = (int)time/60;
    int second = time - minute*60;
    
    NSString *dural;
    if (minute/10 == 0 && second/10 == 0) {
        dural= [NSString stringWithFormat:@"0%d:0%d",minute,second];
    }
    else if (minute/10 != 0 && second/10 == 0) {
        dural= [NSString stringWithFormat:@"%d:0%d",minute,second];
    }
    else if (minute/10 == 0 && second/10 != 0)
    {
        dural = [NSString stringWithFormat:@"0%d:%d",minute,second];
    }
    else
    {
        dural = [NSString stringWithFormat:@"%d:%d",minute,second];
    }
    
    if (  time<0) {
        dural = @"超时十分钟";
    }
    else if (time >= 10*60)
    {
        dural = @"10:00";
    }
    label.text = dural;
    return dural;
}
#pragma mark - request

- (void)queryOrderRequest
{
    QueryOrderReqBuilder *builder = [[QueryOrderReqBuilder alloc]init];
    [builder setStatus:@"1,2"];
    [[ViewRoomLogic shareInstance]queryOrderReqWithBuild:builder.build];
}

- (void)StewardOrderReqWithOrderID:(UInt32)orderID andFinishBlock:(RequestStewardFinishBlock)block
{
    if (finishBlock) {
        finishBlock = nil;
    }
    finishBlock=block;
    
    
    StewardOrderReqBuilder *builder = [[StewardOrderReqBuilder alloc]init];
    
    [builder setOrderStewardId:[[UserLogic shareInstance]getUserId]];
    
    [builder setViewOrderId:orderID];
    
    [[ViewRoomLogic shareInstance]stewardOrderReqWithBuild:builder.build];
    
}

- (void)orderDataChanged:(NSNotification *)noti
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_tableView.header endRefreshing];
        
        if (noti.object == nil) {
         return ;   
        }
        else if ([noti.object isKindOfClass:[ErrorModel class]]) {
            
            ErrorModel *model = noti.object;
            [UIViewCategory FailShowWith:model];
            return ;
        }
        else
        {
            NSString *status = noti.object;
            if ([status isEqualToString:@"1"] || [status isEqualToString:@"2"]) {
                [self reloadData];
            }
        }
        
        
    });

}

-(void)reloadData {
    [dataArray setArray:[[ViewRoomLogic shareInstance]getOrderModelArray_1_2]];
    [self resetBadegeNum:dataArray];
    [self startTimerWith:dataArray];
    [_tableView reloadDataAndisNil:dataArray.count nitText:@"当前无订单信息"];
}

- (void)requestSuccessSteward:(NSNotification *)noti
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([noti.object isKindOfClass:[ViewOrder class]]) {
            if (finishBlock) {
                finishBlock(YES);
                
            }

            
        }
        else if ([noti.object isKindOfClass:[ErrorModel class]])
        {
            ErrorModel *model = noti.object;
            [UIViewCategory FailShowWith:model];
            
            if (finishBlock) {
                finishBlock(NO);
            }
        }
        
        });
}

#pragma mark - events
//修改badge
- (void)resetBadegeNum:(NSArray *)array
{
    UITabBarItem *orderItem = self.tabBarController.tabBar.items[0];
    NSInteger num = 0;
    for (ViewOrderModel *model in dataArray) {
        if ([model.statusStr isEqualToString:@"1"]) {
            num ++;
        }
        
    }
    orderItem.badgeValue = num == 0?nil:[NSString stringWithFormat:@"%ld",(long)num];
    
    
}
- (void)orderCellCallPhone:(UIButton *)btn andCell:(OrderCell *)cell
{
    NSIndexPath *path = [_tableView indexPathForCell:cell];
    
    ViewOrderModel *model = dataArray[path.row];
    
    [KMCheckTel dialPhoneNumber:model.order.phone withView:self.view];
}

- (void)orderCellGetNewOrder:(UIButton *)btn andCell:(OrderCell *)cell
{
    NSIndexPath *path = [_tableView indexPathForCell:cell];
    
    ViewOrderModel *model = dataArray[path.row];
    KMAlertView  *alert0 = [[KMAlertView alloc]initWithTitle:@"确认接单" message:@"这个客户我来搞定！" cancelButtonTitle:@"还是算了" clickButton:^(NSInteger index) {
        
        if (index == 1) {
            HUDShow(@"");
            
            [self StewardOrderReqWithOrderID:model.order.id andFinishBlock:^(BOOL isFinish) {
                HUDRemove;
                
                if (isFinish == NO) {
                    
                }
                if (isFinish == YES) {
                    
                    NSString *message = [NSString stringWithFormat:@"恭喜！您已成功接单，是否立即与客户%@(%@)联系？",model.order.name,model.order.phone];
                    
                    KMAlertView  *alert = [[KMAlertView alloc]initWithTitle:@"成功接单" message:message cancelButtonTitle:@"稍后再说" clickButton:^(NSInteger index) {
                        
                        [self queryOrderRequest];
                        
                        if (index == 0) {
                            cell.orderBtn.hidden = YES;
                            cell.phoneBtn.hidden = NO;
                        }
                        else
                        {
                            cell.orderBtn.hidden = YES;
                            cell.phoneBtn.hidden = NO;
                            [KMCheckTel dialPhoneNumber:model.order.phone withView:self.view];
                        }
                        
                    } otherButtonTitles:@"立即联系"];
                    
                    
                    [alert show];
                    
                }
                finishBlock = nil;
            }];
        }
        
    } otherButtonTitles:@"确定"];
    
    [alert0 show];
    
    
    
}

- (void)clickRoom:(UIBarButtonItem *)item
{
    WebViewController *web = [[WebViewController alloc]init];
    web.urlStr = @"http://180.150.186.187/show/public/Room/list?src=preview";
    HideTabbar(web);
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ViewOrderModel *model = dataArray[indexPath.row];
    if ([model.statusStr isEqualToString:@"1"]) {
        GetOrderViewController *vc = [[GetOrderViewController alloc]init];
        vc.model = model;
        HideTabbar(vc);
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    else
    {
        OrderInfoViewController *info;
        info= [[OrderInfoViewController alloc]initWithNibName:@"OrderInfoViewController" bundle:nil];
        
        info.orderInfo = model.order;
        
        
        HideTabbar(info);
        [self.navigationController pushViewController:info animated:YES];
    }
    

    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"OrderCell";
    OrderCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"OrderCell_6" bundle:nil] forCellReuseIdentifier:CellIdentifier];
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
    }
    ViewOrderModel *model = dataArray[indexPath.row];
    
    [cell setCellOrder:model.order];
    
    cell.delegate = self;
    
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 176;
    
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
#ifdef __IPHONE_8_0
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
#endif
    
}


@end
